Data Storage in Android: SharedPreferences

Table of Contents

We have several data storage solutions for Android app development.

SharedPreferences

SharedPreferences is a light-weight storage for Android to read and store key-value pairs, which is suitable for simple data like app configs, user preferences, login state.

SharedPreferences is, in essence, an .xml file under app-private folder /data/data/<package_name>/shared_prefs.

How to Use?

Retrieval

We mainly have 2 ways to retrieve the SharedPreferences object.

  1. getSharedPreferences(String name, int mode)

    This method is suitable for scenarios like multiple configurations or the config file should be shared among different components.

    Here, the name argument tells the file name of the config file. The mode argument is usually Context.MODE_PRIVATE, which means this file can only be accessed by current app.

      SharedPreferences userPrefs = getSharedPreferences("user_settings", Context.MODE_PRIVATE);
    
  2. getPreferences(int mode)

    This method is a shortcut for activities to create default, private configuration file, whose name is default to activity’s class name.

    This method is only suitable for preference configs within same activity.

      SharedPreferences activityPrefs = getPreferences(Context.MODE_PRIVATE);
    

Writing Data

Writing data is proxied by SharedPreferences.Editor object and follows 3 steps.

  1. invoke edit() method to get Editor instance
  2. invoke putXXX() method to modify or add data, e.g., putString(), putInt(), putBoolean()
  3. invoke apply() or commit() to submit modification.
  // 1. get SharedPreferences.Editor
  SharedPreferences.Editor editor = getSharedPreferences("app_config", Context.MODE_PRIVATE).edit();

  // 2. put data
  editor.putString("username", "AndroidDev");
  editor.putInt("login_count", 5);

  // 3. submit change
  editor.apply();

The key difference between apply() and commit() is about async or sync, which drastically affect speed.

Feature apply() commit()
Execution Async Sync
Return value / boolean to indicate success
Blocking Non-Blocking Blocking
Performance Higher Lower
Data consistency No guarantee Immediate ensure

In most cases, we should use apply()

Reading Data

We just simply invoke getXXX() of SharedPreferences objects.

EncryptedSharedPreferences

Standard SharedPreferences stores data in bear xml files. If we want to store passwords, tokens, we should use EncryptedSharedPreferences, which automatically encrypts keys and values.

First, we have to add dependency in build.gradle of AndroidX Security library.

  dependencies {
    implementation "androidx.security:security-crypto:1.1.0-alpha06"
  }

Date: 2026-05-28 Thu 00:00